package com.zkthink.ceres.shoppingcart.converter;

import com.zkthink.ceres.product.vo.ShoppingCartSkuItemVO;
import com.zkthink.dozer.DozerUtils;
import com.zkthink.ceres.product.vo.ShoppingCartSkuVO;
import com.zkthink.ceres.shoppingcart.dto.ShoppingCartSkuDTO;
import com.zkthink.ceres.shoppingcart.entity.ShoppingCart;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *     购物车 bean 转换器
 * </p>
 *
 * @author vivi.huang
 * @since 2020/5/19
 */
@Component
@AllArgsConstructor
public class ShoppingCartBeanConverter implements Serializable {

    private static final long serialVersionUID = -5033435670614939622L;

    private DozerUtils dozerUtils;

    public List<ShoppingCartSkuDTO> convertToSkuDTOList(List<ShoppingCartSkuVO> shoppingCartSkuVOList) {
        List<ShoppingCartSkuDTO> skuList = Lists.newArrayList();
        for (ShoppingCartSkuVO s: shoppingCartSkuVOList) {
            for (ShoppingCartSkuItemVO sku: s.getShoppingCartSkuItemList()) {
                ShoppingCartSkuDTO shoppingCartSkuDTO = dozerUtils.map(sku, ShoppingCartSkuDTO.class);
                shoppingCartSkuDTO.setStoreId(s.getStoreId());
                shoppingCartSkuDTO.setStoreSelected(s.getSelected());
                skuList.add(shoppingCartSkuDTO);
            }
        }
        return skuList;
    }

    public List<ShoppingCart> convertToShoppingSaveDTOList(Long memberId, List<ShoppingCartSkuVO> shoppingCartSkuVOList) {
        List<ShoppingCart> shoppingCarts = Lists.newArrayList();
        for (ShoppingCartSkuVO shoppingCartSkuVO: shoppingCartSkuVOList) {
            shoppingCarts.addAll(createShoppingCarts(memberId, shoppingCartSkuVO));
        }
        return shoppingCarts;
    }

    private List<ShoppingCart> createShoppingCarts(Long memberId, ShoppingCartSkuVO shoppingCartSkuVO) {
        return shoppingCartSkuVO.getShoppingCartSkuItemList().stream().map(shoppingCartSkuItemVO -> {
            ShoppingCart shoppingCart = dozerUtils.map(shoppingCartSkuItemVO, ShoppingCart.class);
            shoppingCart.setAddTime((int) (System.currentTimeMillis() / 1000));
            shoppingCart.setMemberId(memberId);
            shoppingCart.setSkuId(shoppingCartSkuItemVO.getId());
            shoppingCart.setIsDelete(0);
            shoppingCart.setId(null);
            return shoppingCart;
        }).collect(Collectors.toList());
    }
}